﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;

namespace FuelDXApplication1
{
    public class HttpClientHelper
    {
        public async static Task<K> RequestUrl<T, K>(string url, string method, MethodType type, T data = default!)
        {
            using HttpClient client = new HttpClient();
            //设置基础地址（应该读取配置文件）
            string baseUrl = url;
            client.BaseAddress = new Uri(baseUrl);
            HttpResponseMessage response = null;
            string context = string.Empty;
            switch (type)
            {
                case MethodType.Get:
                    response = await client.GetAsync(method);
                    //判断是否成功   状态码 200
                    if (response.IsSuccessStatusCode)
                    {
                        //读取json
                        context = await response.Content.ReadAsStringAsync();
                        //反序列化
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<K>(context);
                        return result;
                    }
                    break;

                case MethodType.Post:
                    var responsePost = await client.PostAsJsonAsync(method, data);
                    //判断是否成功   状态码 200
                    if (responsePost.IsSuccessStatusCode)
                    {
                        //读取json
                        context = await responsePost.Content.ReadAsStringAsync();
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<K>(context);
                        return result;
                    }
                    break;
                case MethodType.Put:
                    var responsePut = await client.PutAsJsonAsync(method, data);
                    if (responsePut.IsSuccessStatusCode)
                    {
                        context = await responsePut.Content.ReadAsStringAsync();
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<K>(context);
                        return result;
                    }
                    break;
                case MethodType.Delete:

                    var responseDelete = await client.DeleteAsync(method);
                    if (responseDelete.IsSuccessStatusCode)
                    {
                        context = await responseDelete.Content.ReadAsStringAsync();
                        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<K>(context);
                        return result;
                    }

                    break;
                default:
                    break;
            }
            return default!;


        }
    }

    public enum MethodType
    {
        Get,
        Post,
        Put,
        Delete
    }
}
